package com.zpkj.portal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zpkj.portal.dto.RequestParameter;
import com.zpkj.portal.dto.ResponseParameter;
import com.zpkj.portal.utils.Constant;
import com.zpkj.portal.utils.JsonUtils;

import tk.mybatis.mapper.util.StringUtil;

/**
 * 安全拦截器
 * @author ChenK 2017-9-1 14:02
 *
 */
@Component
public class SecurityInterceptor implements HandlerInterceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(SecurityInterceptor.class);

	
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		String requestSource = request.getParameter("requestSource");
		String jsonParams = request.getParameter("jsonParams");
		// 请求参数
		RequestParameter params = JsonUtils.fromEncryptJson(jsonParams, RequestParameter.class, requestSource);
		ResponseParameter result = new ResponseParameter("SecurityInterceptor.preHandle",params.getHeader(),requestSource);
		// 获取userId
		String loginUserId = params.getHeader().getLoginUserId();
		if (StringUtil.isEmpty(loginUserId)) {
			loginUserId=params.getValueFromBody("loginUserId");
		}

		//获取app类型
		String db_token = "hEPmsUjvbDw4AFDavQ7Qx8Upw+ok2t3eUC6RQ0RPlDT0iKMeZFjUUwwXczHCp6";
		String token = params.getHeader().getToken();
		if (StringUtil.isNotEmpty(token) && token.equals(db_token)) {
			logger.info("token验证通过------->>>>>");
		} else {
	        String json = result.addData(null).setResultCode(Constant.ReturnCode.CODE_1888).toJson();
			logger.info("请求返回: token验证失败="+token+"，db_token=" + db_token);
			response.getWriter().write(json);
			return false;
		}
		
		// 获取macNo
		String macNo = params.getHeader().getMacNo();
		String appDeviceType = params.getHeader().getAppDeviceType();
		String ip = request.getRemoteAddr();
		logger.info("--------登录认证 user:" + loginUserId + " macNo:" + macNo + " ip:" + ip+"   appDeviceType"+appDeviceType+"---------");
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {
	}

}